/*
 * @(#)BinaryLogic.java	1.0 Apr 26, 2008
 *
 *	The MIT License
 *
 *	Copyright (c) 2008 Malachi de AElfweald <malachid@gmail.com>
 *
 *	Permission is hereby granted, free of charge, to any person obtaining a copy
 *	of this software and associated documentation files (the "Software"), to deal
 *	in the Software without restriction, including without limitation the rights
 *	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *	copies of the Software, and to permit persons to whom the Software is
 *	furnished to do so, subject to the following conditions:
 *
 *	The above copyright notice and this permission notice shall be included in
 *	all copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *	THE SOFTWARE.
 */
package org.eoti.math;

import org.eoti.io.args4j.CommandLineApp;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;

import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BinaryLogic extends CommandLineApp
{
	@Option(name="-expr", usage="expression, ex: ((var1 | var2) & (var2 ^ var1))", required=true)
	protected String expression;

	public static void main(String[] args)
	{
		try{
			new BinaryLogic(args);
		} catch(Exception e){
			System.err.format("Error: %s\n", e.getMessage());
			e.printStackTrace();
		}
	}

	protected void processArguments(List<String> arguments)
			throws CmdLineException
	{
		if(arguments.size() == 0)
			throw new CmdLineException("No variables specified");
	}

	protected void printExample(CmdLineParser cmdLineParser)
	{
		System.err.println("EXAMPLE: java org.eoti.math.BinaryLogic -expr \"((var1 | var2) & (var2 ^ var1))\" var1=1 var2=0\n");
	}

	public BinaryLogic(String[] args)
			throws CmdLineException
	{
		super(args);
		HashMap<String,Boolean> vars = new HashMap<String,Boolean>();
		try{
			for(String arg : arguments)
			{
				int eqIndex = arg.indexOf("=");
				String variable = arg.substring(0,eqIndex);
				String value = arg.substring(eqIndex+1);
				if(value.equals("1"))
					vars.put(variable, true);
				else if(value.equals("0"))
					vars.put(variable, false);
				else throw new Exception("value="+ value);

//				System.out.println("Variable '" + variable + "'=" + vars.get(variable));
			}
		} catch(Exception e){
			throw new CmdLineException("Incorrect format: Should be variable=1 or variable=0");
		}

		evaluate(expression, vars);
	}

	protected static final String whitespace="\\s*";
	protected static final String variableName = "([A-Za-z0-9_-]+)";
	protected static final String start="\\(";
	protected static final String end="\\)";

	public enum Operand
	{
		AND(start+whitespace+variableName+whitespace+"\\&"+whitespace+variableName+whitespace+end, '&'),
		OR(start+whitespace+variableName+whitespace+"\\|"+whitespace+variableName+whitespace+end, '|'),
		XOR(start+whitespace+variableName+whitespace+"\\^"+whitespace+variableName+whitespace+end, '^'),
		NOT(start+whitespace+"[\\~\\!]"+variableName+whitespace+end, '!', '~');

		Operand(String spec, char ... reps)
		{
			this.reps = reps;
			this.spec = spec;
			this.pattern = Pattern.compile(spec, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
		}
		protected char[] reps;
		protected Pattern pattern;
		protected String spec;
		public char[] getRepresentations(){return reps;}
		public Pattern getPattern(){return pattern;}
		public String getSpec(){return spec;}
	}

	protected boolean evaluate(Operand op, boolean ... vars)
	{
		switch(op)
		{
			case AND:
				return vars[0] & vars[1];
			case OR:
				return vars[0] | vars[1];
			case XOR:
				return vars[0] ^ vars[1];
			case NOT:
				return !vars[0];
		}

		// can't happen
		return false;
	}

	protected HashMap<String,Boolean> variables;
	protected String originalLogic;
	protected String currentLogic;
	protected int tempVar = 1;

	public BinaryLogic(String logic, HashMap<String,Boolean> variables)
	{
		evaluate(logic, variables);
	}

	protected void evaluate(String logic, HashMap<String,Boolean> variables)
	{
		this.originalLogic = logic;
		this.variables = variables;
		this.currentLogic = logic;

		recurse();
//		System.out.println("------------------------------------");
//		System.out.println("REMAINING LOGIC: " + currentLogic);
//		System.out.println("VALUE: " + variables.get(currentLogic));
//		System.out.println("VARIABLES:");

		String result = String.format("%s = %s\n", logic, currentLogic);
		for(String variable : variables.keySet())
			result = result.replaceAll(variable, (variables.get(variable)?"1":"0"));

		System.out.println(result);

//		for(String variable : variables.keySet())
//		{
//			boolean value = variables.get(variable);
//			System.out.println(variable + " = " + (value?"1":"0"));
//		}
	}

	protected void recurse()
	{
		boolean resolved = false;
		if(resolved(Operand.AND)) resolved = true;
		if(resolved(Operand.OR)) resolved = true;
		if(resolved(Operand.XOR)) resolved = true;
		if(resolved(Operand.NOT)) resolved = true;
		if(!resolved) return;
		recurse();
	}

	protected boolean resolved(Operand op)
	{
//		System.out.println("------------------------------------");
//		System.out.println("currentLogic: " + currentLogic);
//		System.out.println("checking: " + op + " ==> " + op.getSpec());
		Matcher matcher = op.getPattern().matcher(currentLogic);
		if(matcher.find())
		{
			String match = matcher.group();
			match = match.substring(1, match.length()-1);// strip ( and )
			int index = -1;
			for(char rep : op.getRepresentations())
			{
//				System.out.println("does '" + match + "' contain '" + rep + "'");
				index = match.indexOf(rep);
				if(index != -1)
					break;
			}
			String var1 = match.substring(0, index).trim();
//			System.out.println("var1 = " + var1 + " = " + variables.get(var1));
			String var2 = match.substring(index+1).trim();
//			System.out.println("var2 = " + var2 + " = " + variables.get(var2));
			boolean result = evaluate(op, variables.get(var1), variables.get(var2));
			String varname = "_TEMPVAR_"+(tempVar++);
//			System.out.println("newVariable: " + varname + " = " + (result?"1":"0"));
			variables.put(varname, result);
			int startPos = matcher.start();
			int endPos = matcher.end();
			currentLogic = currentLogic.substring(0,startPos)+" "+varname+" "+currentLogic.substring(endPos);
			currentLogic = currentLogic.trim();
//			System.out.println("newLogic: " + currentLogic);
			return true;
		}
//		System.out.println("No " + op + " routines found...");
		return false;
	}
}
